import axios from "axios";
import Cookies from "js-cookie";
import { TOKEN_KEY } from "@/utils/utils.js";
import main_config from "@/config";
import Vue from "vue";
import qs from "qs";
import router from "@/router.js";
import { setToken } from "@/utils/utils";
class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl;
    this.queue = {};
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    };
    return config;
  }
  destroy(url) {
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        // 添加全局的loading...
        if (!Object.keys(this.queue).length && url !== 'front/imageModuleList' && url !== 'front/seckill/commoditySecKill') {
          Vue.prototype.$dialog.loading.open("加载中");
        }
        this.queue[url] = true;
        if (!config.url.includes("authenticate")) {
          let token = Cookies.get(TOKEN_KEY);
          if (token) {
            config.headers["Authorization"] = `Bearer ${token}`;
          }
        }
        //解决IOS12下post请求无效的场景
        // if (config.method === 'post') {
        //   config.headers['Content-Type'] =
        //     'application/x-www-form-urlencoded;charset=utf-8'
        //   config.data = qs.stringify(config.data)
        // }
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        Vue.prototype.$dialog.loading.close();
        this.destroy(url);
        const { data, status } = res;
        if (status === 401) {
          let token = Cookies.get(TOKEN_KEY);
          if (token) {
            Cookies.remove(TOKEN_KEY);
            Vue.prototype.$dialog.toast({
              mes: "登录状态失效,请重新登录"
            });
          } else {
            Vue.prototype.$dialog.toast({
              mes: "未登录,请登录后再访问"
            });
          }
        }

        return { data, status };
      },
      error => {
        this.destroy(url);
        if (error instanceof Object == true) {
          Vue.prototype.$dialog.loading.close();
          if (error.response) {
            let data = error.response.data;
            let status = error.response.status;
            // let showError = (show = true) => {
            //   if (show) {
            switch (status) {
              case 400:
                if (data instanceof Object == true) {
                  if (data.msg) {
                    // Message.error(data.msg)
                  } else if (data.data) {
                    // Message.error(data.data)
                  }
                } else {
                  // Message.error(JSON.stringify(data))
                }
                break;
              case 401:
                if (
                  window.location.hash.indexOf("#/vip-invite") !== -1 ||
                  window.location.hash.indexOf("#/main-login") !== -1 ||
                  window.location.hash.indexOf("#/mall") !== -1
                ) {
                  
                  // console.log(1);
                } else {
                  
                  let token = Cookies.get(TOKEN_KEY);

                  if (token) {
                    Cookies.remove(TOKEN_KEY);
                    Vue.prototype.$dialog.toast({
                      mes: "登录状态失效,请重新登录"
                    });
                  } else {
                    Vue.prototype.$dialog.toast({
                      mes: "未登录,请登录后再访问"
                    });
                  }
                  router.replace("/main-login");
                }
                break;
              default:
                // console.log(data);
                Vue.prototype.$dialog.toast({
                  mes: data.message
                });
            }
            //   }
            // }
            // showError(true)
            return { data, status };
          }
        } else {
          Vue.prototype.$dialog.loading.close();
          Vue.prototype.$dialog.toast({
            mes: error.response.data.message
          });
          return Promise.reject(false);
        }
      }
    );
  }
  request(options) {
    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, options.url);
    return instance(options);
  }
}

const baseUrl =
  process.env.NODE_ENV === "development"
    ? main_config.baseUrl.dev
    : main_config.baseUrl.pro;

const axios_request = new HttpRequest(baseUrl);
export default axios_request;
